<template>
  <div class="flex" :class="message.role === 'user' ? 'justify-end' : 'justify-start'">
    <!-- AI消息 -->
    <div v-if="message.role === 'assistant'" class="flex items-start space-x-3">
      <!-- AI头像 - 完全独立的元素，与气泡分离 -->
      <div class="w-8 h-8 bg-primary-100 rounded-full flex items-center justify-center flex-shrink-0 mt-1 shadow-sm">
        <svg class="w-4 h-4 text-primary-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
        </svg>
      </div>
      
      <!-- AI消息气泡 - 完全独立的元素，与头像分离 -->
      <div class="bg-white border border-gray-200 rounded-xl shadow-md hover:shadow-lg transition-all duration-300 px-4 py-3 max-w-xs sm:max-w-sm md:max-w-md lg:max-w-lg xl:max-w-xl break-words overflow-wrap-anywhere">
        <div class="text-sm text-gray-600 mb-1 font-medium">AI Art Assistant</div>
        <div class="text-sm message-content text-gray-800">
          <div v-if="message.status === 'sending' && !message.content" class="text-gray-400 italic">
            AI正在思考中...
          </div>
          <div v-else-if="message.content" v-html="formattedContent"></div>
          <div v-else class="text-gray-400 italic">
            AI正在思考中...
          </div>
        </div>
        
        <!-- 消息状态 -->
        <div class="flex items-center justify-between mt-2">
          <div class="text-xs text-gray-400">
            {{ formatTime(message.timestamp) }}
          </div>
          <div class="flex items-center space-x-1">
            <!-- 重试按钮 -->
            <button
              v-if="message.status === 'error'"
              @click="$emit('retry', message.id)"
              class="text-red-500 hover:text-red-700 text-xs px-2 py-1 rounded hover:bg-red-50 transition-colors"
            >
              Retry
            </button>
            
            <!-- 复制按钮 -->
            <button
              @click="copyMessage"
              class="text-gray-400 hover:text-gray-600 text-xs px-2 py-1 rounded hover:bg-gray-100 transition-colors"
              title="Copy message"
            >
              <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
              </svg>
            </button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 用户消息 -->
    <div v-else class="flex items-start space-x-3 justify-end">
      <!-- 用户消息气泡 - 完全独立的元素，与头像分离 -->
      <div class="bg-primary-600 text-white border border-primary-500 rounded-xl shadow-md hover:shadow-lg transition-all duration-300 px-4 py-3 max-w-xs sm:max-w-sm md:max-w-md lg:max-w-lg xl:max-w-xl break-words overflow-wrap-anywhere">
        <div class="text-sm message-content">
          <div v-if="message.status === 'sending' && !message.content" class="text-white/60 italic">
            正在发送...
          </div>
          <div v-else-if="message.content" v-html="formattedContent"></div>
          <div v-else class="text-white/60 italic">
            正在发送...
          </div>
        </div>
        
        <!-- 消息状态 -->
        <div class="flex items-center justify-between mt-2">
          <div class="text-xs text-white/70">
            {{ formatTime(message.timestamp) }}
          </div>
          <div class="flex items-center space-x-1">
            <!-- 重试按钮 -->
            <button
              v-if="message.status === 'error'"
              @click="$emit('retry', message.id)"
              class="text-red-300 hover:text-red-200 text-xs px-2 py-1 rounded hover:bg-red-500/20 transition-colors"
            >
              Retry
            </button>
            
            <!-- 复制按钮 -->
            <button
              @click="copyMessage"
              class="text-white/60 hover:text-white/80 text-xs px-2 py-1 rounded hover:bg-white/10 transition-colors"
              title="Copy message"
            >
              <svg class="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
              </svg>
            </button>
          </div>
        </div>
      </div>
      
      <!-- 用户头像 - 完全独立的元素，与气泡分离 -->
      <div class="w-8 h-8 bg-primary-100 rounded-full flex items-center justify-center flex-shrink-0 mt-1 shadow-sm">
        <svg class="w-4 h-4 text-primary-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
        </svg>
      </div>
    </div>
  </div>
  
  <!-- 图片模态框 -->
  <div 
    v-if="showImageModal" 
    class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50"
    @click="closeImageModal"
  >
    <div class="relative max-w-4xl max-h-[90vh] bg-white rounded-lg overflow-hidden shadow-2xl">
      <!-- 关闭按钮 -->
      <button
        @click="closeImageModal"
        class="absolute top-4 right-4 z-10 bg-black bg-opacity-50 text-white rounded-full p-2 hover:bg-opacity-70 transition-all duration-200"
      >
        <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
        </svg>
      </button>
      
      <!-- 图片 -->
      <img 
        :src="modalImageUrl" 
        alt="Generated Image" 
        class="max-w-full max-h-[90vh] object-contain"
        @error="handleImageError"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, onMounted, onUnmounted } from 'vue'
import type { ChatMessage as ChatMessageType } from '../../types/chat'

interface Props {
  message: ChatMessageType
}

const props = defineProps<Props>()

const emit = defineEmits<{
  retry: [messageId: string]
}>()

// 图片模态框状态
const showImageModal = ref(false)
const modalImageUrl = ref('')

// 计算属性

const formattedContent = computed(() => {
  let content = props.message.content
  console.log('Processing content:', content) // 调试日志
  
  // 首先尝试解析JSON格式的回复（包含图片）
  try {
    // 检查是否包含image_url关键词
    if (content.includes('image_url')) {
      console.log('Content contains image_url, attempting to parse JSON')
      
      // 先清理内容，处理可能的换行问题
      let cleanedContent = content
        .replace(/\n/g, ' ') // 将换行符替换为空格
        .replace(/\s+/g, ' ') // 将多个空格合并为一个
        .trim()
      
      console.log('Cleaned content:', cleanedContent)
      
      // 尝试多种JSON匹配模式
      let jsonMatch = cleanedContent.match(/\{[^{}]*"image_url"[^{}]*\}/)
      
      // 如果第一种模式没匹配到，尝试更宽松的匹配
      if (!jsonMatch) {
        jsonMatch = cleanedContent.match(/\{[\s\S]*?"image_url"[\s\S]*?\}/)
      }
      
      // 如果还是没匹配到，尝试匹配整个JSON对象
      if (!jsonMatch) {
        jsonMatch = cleanedContent.match(/\{[\s\S]*\}/)
      }
      
      // 如果原始内容没匹配到，尝试在原始内容中匹配
      if (!jsonMatch) {
        jsonMatch = content.match(/\{[\s\S]*\}/)
      }
      
      // 如果还是没匹配到，尝试匹配包含中文前缀的JSON
      if (!jsonMatch) {
        // 匹配类似 "我来帮您生成一张图片!我已经为您生成了以下图片:\n{\n\"prompt\":\"七龙珠\",\n\"image_url\": \"https://...\"\n}" 的格式
        jsonMatch = content.match(/[\s\S]*?(\{[\s\S]*?"image_url"[\s\S]*?\})[\s\S]*?/)
        if (jsonMatch) {
          jsonMatch[0] = jsonMatch[1] // 只保留JSON部分
        }
      }
      
      // 如果还是没匹配到，尝试更宽松的匹配（处理跨行JSON）
      if (!jsonMatch) {
        // 匹配任何包含image_url的JSON对象，即使前面有中文文本
        const lines = content.split('\n')
        for (let i = 0; i < lines.length; i++) {
          if (lines[i].includes('{') && content.includes('image_url')) {
            // 找到包含{的行，从这一行开始匹配到包含}的行
            let jsonStart = i
            let jsonEnd = i
            for (let j = i; j < lines.length; j++) {
              if (lines[j].includes('}')) {
                jsonEnd = j
                break
              }
            }
            if (jsonEnd > jsonStart) {
              const jsonLines = lines.slice(jsonStart, jsonEnd + 1)
              const jsonStr = jsonLines.join('\n')
              if (jsonStr.includes('image_url')) {
                jsonMatch = [jsonStr]
                break
              }
            }
          }
        }
      }
      
      if (jsonMatch) {
        let jsonStr = jsonMatch[0]
        console.log('Found JSON match:', jsonStr) // 调试日志
        
        // 清理JSON字符串，处理换行和格式问题
        jsonStr = jsonStr
          .replace(/\n/g, ' ') // 移除换行
          .replace(/\s+/g, ' ') // 合并多个空格
          .replace(/"image_url"\s*:\s*"([^"]*?)\s*"/g, '"image_url":"$1"') // 修复image_url的换行问题
          .trim()
        
        console.log('Cleaned JSON string:', jsonStr)
        
        const jsonData = JSON.parse(jsonStr)
        console.log('Parsed JSON data:', jsonData) // 调试日志
        
        if (jsonData.image_url) {
          // 构建包含图片的HTML内容
          let htmlContent = ''
          
          // 如果有prompt，显示提示词
          if (jsonData.prompt) {
            htmlContent += `<div class="image-prompt mb-3">
              <div class="text-sm text-gray-600 mb-2 font-medium">Prompt:</div>
              <div class="bg-gray-50 p-3 rounded-lg text-sm">${jsonData.prompt}</div>
            </div>`
          }
          
          // 显示图片
          htmlContent += `<div class="generated-image mb-3">
            <div class="text-sm text-gray-600 mb-2 font-medium">Generated Image:</div>
            <div class="image-container">
              <img 
                src="${jsonData.image_url}" 
                alt="Generated Image" 
                class="max-w-full h-auto rounded-lg shadow-md hover:shadow-lg transition-shadow duration-300 cursor-pointer generated-image-click"
                data-image-url="${jsonData.image_url}"
                loading="lazy"
              />
            </div>
          </div>`
          
          // 不显示JSON数据，只显示图片
          return htmlContent
        }
      }
    }
  } catch (error) {
    console.log('JSON parsing failed:', error)
    console.log('Not a JSON format, proceeding with normal markdown processing')
  }
  
  // 如果不是JSON格式，进行正常的markdown渲染
  // 处理换行
  content = content.replace(/\n/g, '<br>')
  
  // 处理代码块 - 添加更好的溢出处理
  content = content.replace(/```([\s\S]*?)```/g, '<pre class="message-code-block"><code>$1</code></pre>')
  
  // 处理行内代码 - 添加更好的溢出处理
  content = content.replace(/`([^`]+)`/g, '<code class="message-inline-code">$1</code>')
  
  // 处理粗体
  content = content.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
  
  // 处理斜体
  content = content.replace(/\*(.*?)\*/g, '<em>$1</em>')
  
  // 处理链接 - 添加溢出处理
  content = content.replace(/(https?:\/\/[^\s]+)/g, '<a href="$1" target="_blank" rel="noopener noreferrer" class="message-link">$1</a>')
  
  return content
})

// 方法
const formatTime = (timestamp: number) => {
  const date = new Date(timestamp)
  return date.toLocaleTimeString('zh-CN', { 
    hour: '2-digit', 
    minute: '2-digit' 
  })
}

const copyMessage = async () => {
  try {
    await navigator.clipboard.writeText(props.message.content)
    // 这里可以添加复制成功的提示
  } catch (err) {
    console.error('复制失败:', err)
  }
}

// 图片相关方法
const openImageModal = (imageUrl: string) => {
  modalImageUrl.value = imageUrl
  showImageModal.value = true
}

const closeImageModal = () => {
  showImageModal.value = false
  modalImageUrl.value = ''
}

const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  img.src = ''
  img.alt = '图片加载失败'
}

// 处理动态生成的图片点击事件
const handleImageClick = (event: Event) => {
  const target = event.target as HTMLElement
  if (target.classList.contains('generated-image-click')) {
    const imageUrl = target.getAttribute('data-image-url')
    if (imageUrl) {
      openImageModal(imageUrl)
    }
  }
}

// 测试JSON解析功能
const testJsonParsing = () => {
  // 测试实际AI返回的格式（模拟截图中的情况）
  const testContent = `我来帮您生成一张图片!我已经为您生成了以下图片:
{
"prompt":"七龙珠",
"image_url": "https://r2.freeps-airedit.com/ugbr247am"
}`
  
  console.log('Testing JSON parsing with line breaks:', testContent)
  
  // 模拟formattedContent的逻辑
  if (testContent.includes('image_url')) {
    console.log('Content contains image_url, attempting to parse JSON')
    
    // 先清理内容，处理可能的换行问题
    let cleanedContent = testContent
      .replace(/\n/g, ' ') // 将换行符替换为空格
      .replace(/\s+/g, ' ') // 将多个空格合并为一个
      .trim()
    
    console.log('Cleaned content:', cleanedContent)
    
    let jsonMatch = cleanedContent.match(/\{[\s\S]*\}/)
    if (jsonMatch) {
      let jsonStr = jsonMatch[0]
      console.log('Test JSON match found:', jsonStr)
      
      // 清理JSON字符串，处理换行和格式问题
      jsonStr = jsonStr
        .replace(/\n/g, ' ') // 移除换行
        .replace(/\s+/g, ' ') // 合并多个空格
        .replace(/"image_url"\s*:\s*"([^"]*?)\s*"/g, '"image_url":"$1"') // 修复image_url的换行问题
        .trim()
      
      console.log('Cleaned JSON string:', jsonStr)
      
      try {
        const jsonData = JSON.parse(jsonStr)
        console.log('Test JSON parsed successfully:', jsonData)
        return true
      } catch (error) {
        console.log('Test JSON parsing failed:', error)
        return false
      }
    }
  }
  return false
}

// 生命周期钩子
onMounted(() => {
  // 使用事件委托来处理动态生成的图片点击
  document.addEventListener('click', handleImageClick)
  
  // 测试JSON解析
  testJsonParsing()
  
  // 强制测试当前消息的JSON解析
  if (props.message.content.includes('image_url')) {
    console.log('Current message contains image_url, testing parsing...')
    const result = formattedContent.value
    console.log('Formatted content result:', result)
  }
})

onUnmounted(() => {
  document.removeEventListener('click', handleImageClick)
})
</script>
